#include "handler.h"

/**
 * @brief g_errorFlag
 */
extern uint8_t g_errorFlag;

/**
 * @brief error type
 */
extern ERROR_TYPE g_errorType;

extern TIM_HandleTypeDef htim1;

extern TIM_HandleTypeDef htim2;

extern TIM_HandleTypeDef htim3;

extern TIM_HandleTypeDef htim4;

extern UPDATE_UI g_updateUi;

extern double g_pidPowerValue;

extern MONO_PriorityTimerNode *bluzzerProccessNode;

extern MONO_PriorityTimerQueue *tim1_queue;

extern ADC_HandleTypeDef hadc1;

void bluzzerSwitch()
{
    HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_3);
}

void pidResultHandler()
{
    g_updateUi |= (0x01 << UPDATE_UI_POWER);
    TIM2->CCR4 = g_pidPowerValue / 4096 * TIM2->ARR;
    HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_4);
}

void adcConvertResultHandler()
{
    g_updateUi |= (0x01 << UPDATE_UI_TEMPERATURE);
}

/**
 * @brief 记录错误读取次数
 */
uint8_t errorCounter = 0;

void errorHandler()
{
    switch (g_errorType)
    {
        // case :
        //   /* code */
        //   break;

    default:
        break;
    }
    HAL_Delay(10);
    oled_clear();
    
    MONO_PushNode(tim1_queue, bluzzerProccessNode);
    oled_show_string(60, 3, "ERROR!", FONT_SIZE_BIG);

    HAL_TIM_Base_Stop_IT(&htim4);
    HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_4);
    HAL_ADC_Stop_IT(&hadc1);

    HAL_Delay(10);
    T12_Init();
    HAL_Delay(10);

    if (errorCounter >= 5)
    {
        // 强制单片机重启
        errorCounter = 0;
        while (1)
        {
        }
    }


    errorCounter++;

    // Error_Handler();
}